/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.dtgenerator.core.rtgen.entitygen.method;

import com.inspur.edp.bef.bizentity.GspBizEntityElement;
import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.bef.dtgenerator.core.rtgen.entitygen.entityimpl.BefEntityImplGenCtx;
import com.inspur.edp.caf.generator.baseInfo.ParameterInfo;
import com.inspur.edp.caf.generator.baseInfo.TypeInfo;
import com.inspur.edp.caf.generator.method.ClassMethodGenerator;
import com.inspur.edp.caf.generator.utils.ExpressionUtils;
import com.inspur.edp.cef.api.message.CefException;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.element.GspElementObjectType;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.gencommon.MediateType;
import com.inspur.edp.cef.generator.overall.GeneratorUtil;
import com.inspur.edp.cef.generator.overall.Utils;
import com.inspur.edp.cef.spi.common.UdtManagerUtil;
import com.inspur.edp.das.commonmodel.IGspCommonObject;
import com.inspur.edp.udt.designtime.api.entity.SimpleDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.UnifiedDataTypeDef;
import java.util.ArrayList;
import java.util.Map;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.SwitchCase;
import org.eclipse.jdt.core.dom.SwitchStatement;
import org.eclipse.jdt.core.dom.ThrowStatement;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;

public class CreateChildEntityDataGenerator extends ClassMethodGenerator {

  private BefEntityImplGenCtx entityImplGenCtx;
  private GspBizEntityObject node;

  public CreateChildEntityDataGenerator(BefEntityImplGenCtx entityImplGenCtx,
      GspBizEntityObject node) {
    this.entityImplGenCtx = entityImplGenCtx;
    this.node = node;
  }

  private static final String paramchildCode = "childCode";
  private static final String paramchildid = "id";


  @Override
  protected java.util.ArrayList<Modifier.ModifierKeyword> getAccessModifiers() {
    return new java.util.ArrayList<Modifier.ModifierKeyword>(java.util.Arrays
        .asList(new Modifier.ModifierKeyword[]{Modifier.ModifierKeyword.PUBLIC_KEYWORD}));
  }

  @Override
  protected boolean getIsOverride() {
    return true;
  }

  @Override
  protected String getMethodName() {
    return "innerCreateChildEntityData";
  }

  @Override
  protected ArrayList<ParameterInfo> getParameterCollection() {
    ArrayList<ParameterInfo> list = new ArrayList<>();
    ParameterInfo parameterInfo = new ParameterInfo();
    parameterInfo.setParamType(new TypeInfo(String.class));
    parameterInfo.setParamName(paramchildCode);
    list.add(parameterInfo);
    parameterInfo = new ParameterInfo();
    parameterInfo.setParamType(new TypeInfo(String.class));
    parameterInfo.setParamName(paramchildid);
    list.add(parameterInfo);
    return list;
  }

  @Override
  protected TypeInfo getReturnType() {
    return new TypeInfo(IEntityData.class);
  }

  @Override
  protected Block buildMethodBody() {
    Block block = ast.newBlock();
    SwitchStatement switchStatement = ast.newSwitchStatement();
    MethodInvocation methodInvocation = ast.newMethodInvocation();
    methodInvocation.setExpression(ast.newSimpleName(paramchildCode));
    methodInvocation.setName(ast.newSimpleName("toLowerCase"));
    switchStatement.setExpression(methodInvocation);
    addObjectCases(switchStatement);
    addDefaultCase(switchStatement);
    block.statements().add(switchStatement);
    return block;
  }

  private void addObjectCases(SwitchStatement switchStatement) {
    Map<String, MediateType> childTypes = entityImplGenCtx.getParentContext()
        .getProjContext().getEntityDataMediateTypes();

    if (childTypes == null || childTypes.size() == 0) {
      return;
    }
    for (IGspCommonObject childNode : node.GetAllChildObjects()) {
      addObjectCase(childNode, childTypes.get(childNode.getCode()), switchStatement);
    }
  }

  private void addObjectCase(IGspCommonObject childNode, MediateType item,
      SwitchStatement switchStatement) {
    SwitchCase switchCase = ast.newSwitchCase();
    switchCase.setExpression(ExpressionUtils.getStringLiteral(ast, childNode.getCode().toLowerCase()));
    switchStatement.statements().add(switchCase);

    Block block = ast.newBlock();
    addNewDataStatement(item, block);
    //addSetIdPropertyStatement(item, block);
    addSetNestedPropertiesStatements(childNode, block);
    addReturnDataStatement(block);
    switchStatement.statements().add(block);
  }

  private void addNewDataStatement(MediateType item, Block block) {
    VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
    variableDeclarationFragment.setName(ast.newSimpleName("data"));

    ClassInstanceCreation classInstanceCreation = ast.newClassInstanceCreation();
    classInstanceCreation.setType(ast.newSimpleType(ast.newName(item.getFullName())));
    variableDeclarationFragment.setInitializer(classInstanceCreation);

    VariableDeclarationStatement variableDeclarationStatement = ast
        .newVariableDeclarationStatement(variableDeclarationFragment);
    variableDeclarationStatement
        .setType(ast.newSimpleType(ast.newName(item.getFullName())));
    block.statements().add(variableDeclarationStatement);
  }

//  private void addSetIdPropertyStatement(MediateType item, Block block) {
//    MethodInvocation methodInvocation = ast.newMethodInvocation();
//    methodInvocation.setName(ast.newSimpleName("setID"));
//    methodInvocation.setExpression(ast.newSimpleName("data"));
//    methodInvocation.arguments().add(ast.newSimpleName(paramchildid));
//    block.statements().add(ast.newExpressionStatement(methodInvocation));
//  }

  private void addSetNestedPropertiesStatements(IGspCommonObject node, Block block) {
    //TODO: 主表也给带进来了, 先兼容一下
    if (node.getParentObject() == null) {
      return;
    }

    for (IGspCommonField field : node.getContainElements()) {
      if (field.getIsUdt()) {
        addSetNestedPropertyStatement(node, block, field);
      } else if (field.getObjectType() == GspElementObjectType.DynamicProp) {
        CreateEntityDataGenerator
            .addSetDynamicPropSetStatement(ast, block, field, entityImplGenCtx);
      }
    }
  }

  private void addSetNestedPropertyStatement(IGspCommonObject node, Block block,
      IGspCommonField field) {
    MethodInvocation methodInvocation = ast.newMethodInvocation();
    methodInvocation.setName(ast.newSimpleName(Utils.getSetterMethodName(field.getLabelID())));
    methodInvocation.setExpression(ast.newSimpleName("data"));
    addCreateDataTypeStatement(methodInvocation, field);
    block.statements().add(ast.newExpressionStatement(methodInvocation));
  }

  private void addCreateDataTypeStatement(MethodInvocation methodInvocation,
      IGspCommonField field) {
    UnifiedDataTypeDef udt = entityImplGenCtx.getEntityGenCtx().getProjContext().getCefGenContext()
        .getMetadataContent(field.getUdtPkgName(), field.getUdtID());

    MethodInvocation createDataInvocation = ast.newMethodInvocation();
    createDataInvocation.setName(ast.newSimpleName("createData"));
    createDataInvocation.setExpression(ast.newName(UdtManagerUtil.class.getTypeName()));
    createDataInvocation.arguments().add(ExpressionUtils.getStringLiteral(ast, udt.getUdtType()));

    if (udt instanceof SimpleDataTypeDef && !((GspBizEntityElement) field).getIsDefaultNull()) {
      Expression defaultValueExpr = CreateEntityDataGenerator
          .getSimpleUdtDefaultValue(ast, (SimpleDataTypeDef) udt);
      if (defaultValueExpr != null) {
        createDataInvocation.arguments().add(defaultValueExpr);
      }
    }

    methodInvocation.arguments().add(createDataInvocation);
  }

  private void addMethodCreateManagerExpression(MethodInvocation methodInvocationCreateManager,
      String objectCode) {
    MethodInvocation methodInvocation = ast.newMethodInvocation();
    methodInvocation.setName(ast.newSimpleName("getUdtFactory"));
    methodInvocation.setExpression(ast.newName(UdtManagerUtil.class.getTypeName()));

    methodInvocationCreateManager.setExpression(methodInvocation);
  }

  private void addReturnDataStatement(Block block) {
    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ast.newSimpleName("data"));
    block.statements().add(returnStatement);
  }

  private void addDefaultCase(SwitchStatement switchStatement) {
    SwitchCase switchCase = ast.newSwitchCase();
    switchCase.setExpression(null);
    switchStatement.statements().add(switchCase);
    addImport(CefException.class.getTypeName());
    ThrowStatement throwStatement = GeneratorUtil.getThrowStatement(ast,null);
//    ClassInstanceCreation classInstanceCreation = ast.newClassInstanceCreation();
//    classInstanceCreation.setType(
//        new com.inspur.edp.caf.generator.baseInfo.TypeInfo(RuntimeException.class).getType(ast));
//    throwStatement.setExpression(classInstanceCreation);
    switchStatement.statements().add(throwStatement);
  }
}
